package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.user.dtos.AuthDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserRealname;
import com.usian.user.feign.ArticleFeign;
import com.usian.user.feign.WemediaFeign;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.mapper.ApUserRealnameMapper;
import com.usian.user.service.ApUserRealnameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ArticleFeign articleFeign;

    @Override
    public PageResponseResult loadListByStatus(AuthDto dto) {
        //参数为空
        if (dto == null) {
            return (PageResponseResult) ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //分页查询
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        Page pageParam = new Page(dto.getPage(),dto.getSize());
        IPage page= page(pageParam,wrapper);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        responseResult.setCode(0);
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 根据状态进行审核
     * @param dto
     * @param status
     * @return
     */

    public static final Short PASS_AUTH = 9;//审核通过
    public static final Short FAIL_AUTH = 2;//审核不通过
    public static final Short AUTHOR_TYPE=2;//平台自媒体人

    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short status) {

        //校验参数
        if (dto == null || dto.getId()==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (this.statusCheck(status)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //更新审核的状态 更新ApUserRealname
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);
        if (dto.getMsg() != null){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);


        //如果通过 ---》wmuser(realname -- userId -- apuser -- ) ---—》apauthor --》update   ap_user_realname   ----》update apuser flag
        //判断是否通过
        if (status.equals(PASS_AUTH)){
            //创建自媒体账号
            ResponseResult responseResult = this.createWmUserAndAuthor(dto);

        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 创建自媒体账号， 以及作者账号
     * @param dto
     * @return
     */


    private ResponseResult createWmUserAndAuthor(AuthDto dto) {
        ApUserRealname userrealname = this.getById(dto.getId());
        ApUser apUser = apUserMapper.selectById(userrealname.getUserId());
        if (apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断wmuser 是否有账号
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if (wmUser == null){
            wmUser = new WmUser();
            //设置ApUserId
            wmUser.setApUserId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setStatus(Integer.valueOf(PASS_AUTH));//标记审核通过
            wmUser.setPhone(apUser.getPhone());
            wemediaFeign.save(wmUser);
        }
        //要写入作者表
        createAuthor(wmUser);
        apUser.setFlag((short)1);
        apUserMapper.updateById(apUser);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 创建自媒体账号
     * @param wmUser
     * @return
     */
    private void createAuthor(WmUser wmUser) {
        Integer apUserId = wmUser.getApUserId();
        ApAuthor apAuthor = articleFeign.findByUserId(apUserId);
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setName(wmUser.getName());
            apAuthor.setType(Integer.valueOf(AUTHOR_TYPE));
            apAuthor.setCreatedTime(new Date());
            apAuthor.setUserId(apUserId);
            articleFeign.saveApauthor(apAuthor);
        }
    }

    private boolean statusCheck(Short status) {
        if (status == null || ( !status.equals(FAIL_AUTH) && !status.equals(PASS_AUTH))) {
            return true;//status == null status == 5,6,7    如果传过来的都不是9,2，那么代表不通过 就返回true ：参数不合格
        }
        return false;//参数合格
    }
}
